<?php

namespace App\Handlers;

use GuzzleHttp\Client;
use Cache;
class ShortUrlHandler
{
    protected $lasttime = 0;
    public function url2short($urls, $type = 'weibo')
    {
      switch ($type) {
        case 'weibo':
          return $this->shortUrl_by_weibo($urls);
          break;
        case 'w_url':
          $result_urls = [];
          foreach($urls as $long) {
            $result_urls[] = $this->shortUrl_by_url_cn($long);
          }
          return $result_urls;
          break;
        default:
          // code...
          break;
      }
    }

    public function shortUrl_by_weibo($urls)
    {
      $http = new Client;
      $api = 'http://api.t.sina.com.cn/short_url/shorten.json?';
      $secret = config('services.weibo.secret');
      $appkey = config('services.weibo.appkey');
      $str = '&url_long=';
      foreach($urls as $url) {
          $str .= urlencode($url) . '&url_long=';
      }

      $str = rtrim($str, '&url_long=');

      $query = http_build_query([
          "source"     =>  $appkey,
      ]);

      $response = $http->get($api.$query.$str);

      $result = json_decode($response->getBody(), true);

      $short_urls = array_column($result, 'url_short');

      return $short_urls;
    }
    public function shortUrl_by_dwz($urls)
    {
      $token = config('services.baidu_dwz.token');
      $http = new Client(['headers' =>
        [
          'Token' => $token,
          'Content-Type' => 'application/json'
        ]
      ]);
      $api = 'https://dwz.cn/admin/v2/create';
      $response = $http->request('POST', $api, ['body' => json_encode(['url' => $urls])]);
      $body = $response->getBody();
      $result = json_decode($response->getBody(), true);
      return $result;
    }
    public function shortUrl_by_url_cn($url)
    {
      do {
        $lasttime = Cache::get('w_url_lasttime', time());
      } while ($lasttime >= time());
      $http = new Client;
      $api = 'http://route.showapi.com/1311-1/?';
      $appid = config('services.showapi.appid');
      $appkey = config('services.showapi.secret');
      $sign = md5('long' . $url . 'showapi_appid' . $appid . $appkey);
      $query = http_build_query([
        'showapi_appid' => $appid,
        'long' => $url,
        'showapi_sign' => $sign
      ]);
      $response = $http->get($api.$query);

      $result = json_decode($response->getBody(), true);
      $expiresAt =  now()->addSeconds(1);
      Cache::put('w_url_lasttime', time(), $expiresAt);
      if ($result['showapi_res_body']['short']) return $result['showapi_res_body']['short'];
      else return $url;
    }
}
